const mergeObject = (a, b, columnName) => {
  for (let key in b) {
    if (key != columnName) {
      if (a.hasOwnProperty(key)) {
        a[key + Math.ceil(Math.random() * 10)] = b[key]
      } else {
        a[key] = b[key]
      }
    }
  }

  return a
}

export const mergeResult = (result, map, mapKeyName, resultKeyName = 'id') => {
  let ret = []

  result.forEach((v) => {
    if (map instanceof Array) {
      map.forEach((b) => {
        if (v[resultKeyName] == b[mapKeyName]) {
          ret.push(mergeObject(v, b, mapKeyName))
        }
      })
    } else if (map instanceof Object) {
      for (let key in map) {
        let value = map[key]

        if (v[resultKeyName] == key) {
          let obj = new Object()
          obj[mapKeyName] = value

          ret.push(mergeObject(v, obj, null))
        }
      }
    }
  })

  return ret
}

export const recursion = (data) => {
  let ret = {}

  data.forEach((v) => {
    if (v.parentId != 0) {
      let parent = ret[v.parentId]

      if (!ret[v.parentId].hasOwnProperty('children')) {
        ret[v.parentId]['children'] = {}
      }

      ret[v.parentId]['children'][v.id] = v
    } else {
      ret[v.id] = v
    }
  })

  return result(Object.values(ret))
}

const getValue = (v) => {
  if (v.hasOwnProperty('children')) {
    v.children = Object.values(v.children)
  }

  return v
}

const result = (data) => {
  for (let i in data) {
    let v = getValue(data[i])

    if (v.hasOwnProperty('children')) {
      v['children'] = result(v.children)
    }

    data[i] = v
  }

  return data
}
